package com.itrus.auth.demo.core;

import com.alibaba.fastjson.JSONObject;
import com.itrus.auth.demo.util.DigestTools;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;

import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;
import java.util.Map;

/**
 * @author : peigen
 * @since: 2023/8/1 18:02
 */
@Slf4j
public abstract class BaseAuth {

    protected Config config;
    protected String AUTHORIZATION = "Authorization";
    protected String APP_ID_KEY = "appId";
    protected String SERVICE_CODE_KEY = "serviceCode";

    protected OkHttpClient client = new OkHttpClient();
    protected MediaType mediaType = MediaType.parse("application/json;charset=utf-8");


    public abstract String getServiceCode();

    protected String doRequest(String requestPath, Map<String, String> requestMap) {
        // 请求数据
        String requestBodyStr = JSONObject.toJSONString(requestMap);

        // 生成签名，签名秘钥为：secretKey + serviceCode
        String key = config.getSecretKey() + getServiceCode();
        String signature = genSignature(requestBodyStr, key);
        // AUTHORIZATION 为固定值 COMMON + 英文空格 + signature
        String authorization = "COMMON " + signature;

        // 发送 http 请求
        RequestBody body = RequestBody.create(mediaType, requestBodyStr);
        Request request = new Request.Builder()
                .url(config.getUrl() + requestPath)
                .addHeader(AUTHORIZATION, authorization)
                .addHeader(APP_ID_KEY, config.getAppId())
                .addHeader(SERVICE_CODE_KEY, getServiceCode())
                .post(body)
                .build();

        log.info("实名认证请求，{}：【{}】，请求内容：【{}】", AUTHORIZATION, authorization, requestBodyStr);
        try {
            Response response = client.newCall(request).execute();
            String result = response.body().string();
            log.info("实名认证响应：【{}】", result);
            return result;
        } catch (IOException e) {
            log.error("实名认证请求异常，requestBody：【{}】", requestBodyStr, e);
        }
        return "实名认证请求异常";
    }

    /**
     * 生成签名
     *
     * @param content
     * @return
     */
    protected String genSignature(String content, String key) {
        try {
            byte[] hmacSha1 = DigestTools.hmacSha1(content.getBytes(), key);
            return Base64.getEncoder().encodeToString(hmacSha1);
        } catch (NoSuchAlgorithmException e) {
            // un reach
            throw new RuntimeException("生成签名异常", e);
        } catch (InvalidKeyException e) {
            // un reach
            throw new RuntimeException("生成签名异常", e);
        }
    }
}
